/*
    This file is part of qmessages.
    Copyright (C) 2010  Jason Newton <nevion@gmail.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "ConnectionManager.h"
#include <QVariant>
#include <QTcpSocket>
#include <QTimer>
#include <QDebug>

ConnectionManager::ConnectionManager(const QString &host, quint16 port, QObject *parent):
    QObject(parent), host(host), port(port), socket(0){
}

ConnectionManager::~ConnectionManager(){
}

void ConnectionManager::onConnect(){
    emit onConnect(socket);//give away the socket
}

void ConnectionManager::connect(){
    //qDebug()<<"cm::connect";
    if(socket == 0){
        socket = new QTcpSocket(0);
        socket->setSocketOption(QAbstractSocket::LowDelayOption, QVariant(1));
        socket->setSocketOption(QAbstractSocket::KeepAliveOption, QVariant(1));

        QObject::connect(socket, SIGNAL(connected()), this, SLOT(onConnect()));
        //QObject::connect(socket, SIGNAL(disconnected()), this, SIGNAL(onDisconnect()));
        QObject::connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(onConnectionError(QAbstractSocket::SocketError)));
    }
    socket->connectToHost(host, port);
}

void ConnectionManager::onConnectionError(QAbstractSocket::SocketError socketError){
    qDebug()<<"Connection problem w/ server:"<<socket->errorString()<<"errnum="<<socketError;
    if(socket->parent() == 0){//it's a socket we own
        //qDebug()<<"cleaning up socket owned by no-one";
        socket->deleteLater();
    }
    socket = 0;
    //qDebug()<<"emitting disconnect";
    emit onDisconnect();
    //qDebug()<<"emitting disconnect after";
    const int delay = 5000;//5 seconds
    qDebug()<<"retrying connection in"<<delay<<"msecs";
    QTimer::singleShot(delay, this, SLOT(connect()));
}
